package com.dmzapp.api.servlet;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dmzapp.api.db.AppDao;
import com.dmzapp.api.service.RedisAndDBService;
import com.dmzapp.api.util.PropsUtils;
import com.dmzapp.api.vo.UserAccount;

/**
 * Servlet implementation class for Servlet: RegistAccountHandler
 * 
 */
public class AccountHandler extends com.dmzapp.api.servlet.DMZSerlvet {
    static final long serialVersionUID = 1L;
    Logger logger = LoggerFactory.getLogger("dmzlog");

    public String getRemortIP(HttpServletRequest request) {

        if (request.getHeader("x-forwarded-for") == null) {

            return request.getRemoteAddr();

        }

        return request.getHeader("x-forwarded-for");

    }

    /*
     * (non-Java-doc)
     * 
     * @see javax.servlet.http.HttpServlet#HttpServlet()
     */
    public AccountHandler() {
        super();
    }

    private ObjectMapper mapper = new ObjectMapper();

    /**
     * 验证用户是否合法 客户端传过来的qq或者sina账号 是否在库中存在，
     * 如果存在,检查mac地址和deviceid是否匹配，如果不匹配表示用了别的手机登陆，系统不支持一个账号在多个手机上登陆，因此是无效的
     * 
     * 
     * 如果不存在，注册！
     * 
     */
    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response) {
        logger.debug("auth from ip: " + getRemortIP((HttpServletRequest) request));
        try {
     
            String username = (String) request.getAttribute("u");

            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("status", "200");
            responseMap.put("server_time", Calendar.getInstance().getTimeInMillis());
            responseMap.put("name", username);
            responseMap.put("amount", RedisAndDBService.getUserAmount(username));
            responseMap.put("rest", RedisAndDBService.getUserRest(username));
            responseMap.put("apkversioncode", PropsUtils.getProperty("apkversioncode"));
            responseMap.put("apkversionname", PropsUtils.getProperty("apkversionname"));
            responseMap.put("apkupdatemessage", PropsUtils.getProperty("apkupdatemessage"));
            responseMap.put("apkdownloadurl", PropsUtils.getProperty("apkdownloadurl"));

            mapper.writeValue(response.getWriter(), responseMap);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}